/**
 * @description 路由拦截状态管理，目前两种模式：all模式与intelligence模式，其中partialRoutes是菜单暂未使用
 */
import { defineStore } from 'pinia'
import LocalStorage from '@/utils/LocalStorage'
import type { appState, userinfoType } from '@/types/app'
import loginApi from '@/service/api/login'

export const useAppsStore = defineStore('app', {
  state: (): appState => ({
    token: '',
    userInfo: {
      photo: '',
      username: '',
      managerName: '',
      remark: '',
      permission: []
    }
  }),
  getters: {
    getToken: state => state.token,
    getLoginStatus: state => !!state.userInfo?.id,
    getUserType: state => state.userInfo?.roleCode,
    getUserInfo: state => state.userInfo
  },
  actions: {
    /**
     * @description 获取用户信息
     * @returns data
     */
    async doUserInfo(): Promise<userinfoType> {
      const { code, data, message } = await loginApi.doInfo()
      if (code !== 200) {
        this.signOut()
        throw message
      }
      this.userInfo = data
      return data
    },
    /**
     * @description 设置token，并且获取用户信息
     * @param token
     * @returns
     */
    async setToken(token: string) {
      LocalStorage.set(import.meta.env.VITE_TOKEN_LOACTION_NAME, token)
      this.token = token
      return await this.doUserInfo()
    },
    /**
     * @description 登出
     * */
    signOut() {
      LocalStorage.remove(import.meta.env.VITE_TOKEN_LOACTION_NAME)
      this.token = ''
      this.userInfo = {
        photo: '',
        username: '',
        roleCode: '',
        managerName: '',
        remark: '',
        permission: []
      }
    }
  }
})
